package com.nulldev.util.web.nTubeExtensions.services.radio;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.HttpClient.HttpResponse;

public class RadioJSR {

	/*
	 * >obfuscated Javascript (You) tried.
	 */

	public static final String[] playlists =
		{ "summer", "halloween", "christmas",
				/* */
				"classic", "future", "ultraremixes", "kingforanotherday", "lofi", "memoriesoftokyoto", "elaquent",
				/* */
				"ggs", "noisetanks", "poisonjam", "rapid99", "loveshockers", "immortals", "doomriders", "goldenrhinos",
				/* */
				"ollieking", "toejamandearl", "crazytaxi", "hover", "butterflies",
				/* */
				"revolution", "endofdays" };

	public static List<String> getTracks(final String playlist) throws Exception {
		final ArrayList<String> n = new ArrayList<String>();
		if (playlist == null || playlist.isEmpty())
			return n;
		if (!ArrayUtils.contains(playlists, playlist))
			return n;
		final String url = "https://jetsetradio.live/radio/stations/" + playlist + "/~list.js";
		final HttpResponse<String> s = HttpClient.getString().url(url).create();
		final String data = s.dataThenClose();
		final String[] o = data.split("\\n|\\r\\n");
		for (int i = 0; i < o.length; i++) {
			if (!o[i].startsWith("this[stationName+'_tracks'][this[stationName+'_tracks'].length] = "))
				continue;
			n.add(StringsUtil.substringBetweenO(o[i], "\"", "\""));
		}
		return n;
	}

	public static String getTrackURL(final String playlist, final String trackName) {
		if (playlist == null || playlist.isEmpty())
			return null;
		if (trackName == null || trackName.isEmpty())
			return null;
		return "https://jetsetradio.live/radio/stations/" + playlist + "/" + trackName.replaceAll(Pattern.quote(" "), "%20") + ".mp3";
	}

	public static void main(String[] args) throws Exception {
		final List<String> tracks = getTracks("kingforanotherday");
		ArrayUtils.printLln(tracks);
		JVM.println("Random Track: " + getTrackURL("kingforanotherday", ArrayUtils.random(tracks)));
	}
}
